package zhuyouyong.bottomtab

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import androidx.core.content.ContextCompat

/**
 * @author zhuyouyong <zhuyouyong@bm-intelligent.com>
 * Created on 2021/6/18.
 */
class CommonTab(context: Context, attrs: AttributeSet? = null) : CustomLayout(context, attrs) {
    private var disableClick = false
    private var clickListener: ((Int) -> Unit)? = null
    private val clickTime = resources.getInteger(R.integer.zyy_click_time).toLong()
    private var currentPos = 0
    private val bgColor = ContextCompat.getColor(context, R.color.zyy_bg_color)
    private val commonColor = ContextCompat.getColor(context, R.color.zyy_common_color)
    private val accentColor = ContextCompat.getColor(context, R.color.zyy_accent_color)
    private val colorStateList = ColorStateList(
        arrayOf(
            intArrayOf(android.R.attr.state_pressed),
            intArrayOf(android.R.attr.state_selected),
            intArrayOf(-android.R.attr.state_selected)
        ),
        intArrayOf(accentColor, accentColor, commonColor)
    )
    private val borderPaint = Paint().apply { color = commonColor }
    private val workHandler = Handler(Looper.getMainLooper())
    private val itemHeight = resources.getDimensionPixelSize(R.dimen.zyy_tab_height)

    override fun setContent(vararg contents: Pair<String, Int>) {
        setWillNotDraw(false)
        clipChildren = false
        val txtSize = resources.getDimensionPixelSize(R.dimen.zyy_text_size)
        items = Array(contents.size) {
            LabelTextView(context).apply {
                textSize = txtSize.toFloat()
                setTextColor(colorStateList)
                gravity = Gravity.CENTER_HORIZONTAL
                /*setPadding(0, 12.dp, 0, 0)*/
                layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
                foreground = ContextCompat.getDrawable(
                    context,
                    context.resourceId(android.R.attr.selectableItemBackgroundBorderless)
                )
                addView(this)
            }
        }

        val drawablePadding = resources.getDimensionPixelSize(R.dimen.zyy_drawable_padding)
        contents.forEachIndexed { index, pair ->
            (items[index] as LabelTextView).apply {
                text = pair.first
                setCompoundDrawablesWithIntrinsicBounds(0, pair.second!!, 0, 0)
                /*TextViewCompat.setCompoundDrawableTintList(this, colorStateList)*/
                compoundDrawablePadding = drawablePadding
                setOnClickListener { onClick(index) }
            }
        }
        items[0].isSelected = true
    }

    fun setLabel(
        index: Int, drawableId: Int,
        paddingStart: Float = 8.dp.toFloat(), paddingTop: Float = 6.dp.toFloat()
    ) {
        (items[index] as LabelTextView).setLabel(drawableId, paddingStart, paddingTop)
    }

    fun setBorderColor(color: Int) {
        borderPaint.color = color
    }

    override fun setClickListener(click: (Int) -> Unit) {
        clickListener = click
    }

    private fun onClick(pos: Int) {
        if (disableClick || currentPos == pos) return
        disableClick = true
        items[currentPos].isSelected = false
        currentPos = pos
        items[currentPos].isSelected = true
        workHandler.postDelayed({
            disableClick = false
            clickListener?.invoke(pos)
        }, clickTime)
    }

    override fun getCurrentPos() = currentPos

    private fun Context.resourceId(attr: Int) = TypedValue().let {
        theme.resolveAttribute(attr, it, true)
        it.resourceId
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, itemHeight.toExactlyMeasureSpec())
        val itemWidth = measuredWidth / items.size
        val itemWidthSpec = itemWidth.toExactlyMeasureSpec()
        items.forEach { it.measure(itemWidthSpec, it.defaultHeightMeasureSpec(this)) }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val y = (measuredHeight - items[0].measuredHeight) / 2
        items.forEachIndexed { index, labelTextView ->
            val previous = index - 1
            val x = if (previous >= 0) items[previous].right else 0
            labelTextView.layout(x, y)
        }
    }

    override fun onDraw(canvas: Canvas) {
        canvas.drawColor(bgColor)
//        canvas.drawLine(0f, 0f, width.toFloat(), 0f, borderPaint)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        workHandler.removeCallbacksAndMessages(null)
    }
}